<template>
  <div class="search-box">
    <!-- 顶部导航 -->
    <form action="/" class="search-bar">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="$router.go(-1)"
        @focus="isShowResult = false"
      />
    </form>
    <!-- 搜索结果 -->
    <SearchResult v-if="isShowResult" :value="searchText" />
    <!-- 搜索历史 -->
    <SearchHistory
      v-else-if="!searchText"
      :history="history"
      @search="onSearch"
    />
    <!-- 联想建议 -->
    <SearchSuggestion v-else :value="searchText" @search="onSearch" />
  </div>
</template>

<script>

import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-result.vue'
import { setItem, getItem } from '@/utils/storage.js'
const HMTT_HISTORY = 'hmtt_history'
export default {
  name: 'search',
  data () {
    return {
      // 搜索关键词
      searchText: '',
      // 搜索结果显隐
      isShowResult: false,
      // 历史记录
      history: getItem(HMTT_HISTORY) || []
    }
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  watch: {
    history (nval) {
      setItem(HMTT_HISTORY, nval)
    }
  },
  methods: {
    onSearch (val) {
      this.history.unshift(val)
      this.history = [...new Set(this.history)]
      this.searchText = val
      this.isShowResult = true
    }
  }
}
</script>

<style scoped lang='less'>
.search-box {
  // 顶部导航
  .search-bar {
    position: sticky;
    top: 0;
    // 取消按钮
    .van-search__action {
      padding: 0 33px;
      font-size: 28px;
      color: #fff;
    }
  }
}
</style>
